<?php
class User
{
	public $id;
    public $email;
    public $password;
	public $gender;
	public $firstname;
	public $surname;
    public $phone;
	public $birth;
	public $address;
	public $picture;
	public $active;
	public $acctype;
	public $regdate;
    public $lastip;
	public $orders; 	
	
	
	public function __construct($db,$id)
    {
		$reponse = $db->query('SELECT * FROM jktrade_users WHERE id='.$id.'');
		$data = $reponse->fetch();
		
		$reponse2 = $db->query('SELECT ord_id FROM jktrade_orders WHERE ord_user='.$id.'');
		$orders = $reponse2->fetchAll(PDO::FETCH_COLUMN);
		
		$this->id=$id;
		$this->email=$data['email'];
		$this->password=$data['pwd'];
		$this->firstname=$data['firstname'];
		$this->surname=$data['surname'];
		$this->phone=$data['phone'];
		$this->birth=$data['birth'];
		$this->address=$data['address'];
		$this->picture=$data['pic'];
		$this->active=$data['active'];
		$this->acctype=$data['acctype'];
		$this->regdate=$data['regdate'];
		$this->lastip=$data['last_ip'];
		$this->orders=$orders;
	}

	public function getRegdate()
    {
		$regdate = strtotime($this->regdate);
		$str_regdate = date('F jS Y', $regdate);
		
        return $str_regdate;
    }
	
	public function getProductsOnSale($db)
    {
		$reponse = $db->query('SELECT pr_id FROM jktrade_products WHERE pr_sellerID='.$this->id.'');
		$data = $reponse->fetchAll(PDO::FETCH_COLUMN);
		
        return $data;
    }
	
	public function getAge()
    {
		$age=calculate_age($this->birth);
		
        return $age;
    }
	
	public function getName()
    {
		$name=$this->firstname . ' ' . $this->surname ;
		
        return $name;
    }
	
	public function updateIP($db)
    {
		$db->exec('UPDATE jktrade_users SET last_ip="'.$_SERVER['REMOTE_ADDR'].'" WHERE id = '.$this->id.'');	
    }
	
	public function updatePassword($db,$newpwd)
    {
		$hash_pwd=sha1($newpwd);
		$db->exec('UPDATE jktrade_users SET pwd="'.$hash_pwd.'" WHERE id = '.$this->id.'');	
    }
	
	public function updateEmail($db,$newmail)
    {
		$db->exec('UPDATE jktrade_users SET email="'.$newmail.'" WHERE id = '.$this->id.'');	
    }
	
	public function updatePhone($db,$newphone)
    {
		$db->exec('UPDATE jktrade_users SET phone="'.$newphone.'" WHERE id = '.$this->id.'');	
    }
	
	public function updateAddress($db,$newaddress)
    {
		$db->exec('UPDATE jktrade_users SET address="'.$newaddress.'" WHERE id = '.$this->id.'');	
    }
	
	public function getInfo()
    {
		echo'<span>First name:</span> '.$this->firstname.'<br/>
			<span>Surname:</span> '.$this->surname.'<br/>
			<span>Age:</span> '.$this->getAge().'<br/>
			<span>Email:</span> '.$this->email.'<br/>
			<span>Phone:</span> '.$this->phone.'<br/>
			<span>Address:</span> '.$this->address.'<br/>
			<span>Account type:</span> <span style="text-transform: capitalize; font-weight: 400;">'.$this->acctype.'</span> - <a href="account.php?sub=upgrade">[upgrade to pro]</a><br/>
			<span>Registration date:</span> '.$this->getRegdate().'<br/>
			<span>Last IP:</span> '.$this->lastip.'<br/>';
    }
	
	public function displaysidemenu($db)
	{
	echo'<div class="col-md-3">
			<img src="img/avatar-default.gif" class="img-rounded" style="border:none"/><br/>
				<h4><span>'. $this->firstname . " " . $this->surname .'</span><br/><a href="">Edit profile picture</a></h4>
			 
				<p>Member since '. $this->getRegdate() .'</p>
				<div style="border:2px solid;padding:10px;border-radius:6px;border-color:#CFD1D1;max-width:203px;">
					<a href="account.php"><i class="fa fa-file-text-o"></i> Summary</a><br>
					<a href="?sub=inbox"><i class="fa fa-envelope"></i> Messages <span class="label label-primary">'. getUnreadAmount($db, $this) .'</span></a><br>
					<a href="?sub=products"><i class="fa fa-reorder"></i> My products</a><br>
					<a href="?sub=orders"><i class="fa fa-ticket"></i> My orders</a><br>
					<a href="?sub=upgrade"><i class="fa fa-send"></i> Upgrade account</a><br>
				</div>
				
			</div>';
			// Deleted for the now: <a href="?sub=settings"><i class="fa fa-wrench"></i> Edit information</a>
	}
	
	public function editInfo($db)
    { // This function allows member to edit his information
		
		
		if(isset($_POST['op']) AND $_POST['op']=="edituser")
		{
			$errors=false;
			// First check: does the "e-mail" seems to be a valid email ? 
			if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) OR empty($_POST['email']))
			{
			$error['mail']="Your e-mail doesn't seem right. It must looks like domain@example.com";
			$errors=true; // if there's an error somewhere, this is true. 
			}

			// Second check: the email may be valid, but does it already exists in the database ?
			$req = $db->prepare('SELECT id FROM jktrade_users WHERE email = :email');
								$req->execute(array('email' => $_POST['email']));
								$result = $req->fetch();

			if($result AND $result['id']!=$this->id)// mail found and is not the actual user email
			{
				$error['mail']="Looks like this email is already used.";	
				$errors=true;
				
			}
			else{
			//Password. Let's see if it is, at least, 6 characters long. This restriction can be modified in config.inc.php
			if((strlen($_POST['password'])<MIN_PWD_LENGHT) AND ($_POST['password'])!="false")
			{
			$error['password']="Looks like your password is less than 6 characters. Pick another one !";
			$errors=true;
			}
			if($_POST['password']!="false" AND $this->password!=sha1($_POST['password'])  AND !isset($error['password']) AND $errors==false) // user wants to change pwd
			{
				$this->updatePassword($db,$_POST['password']);
				updatecookie(sha1($_POST['password']));
				$norefresh=true;
			}
			else
			{
			$norefresh=false;
			}
			
			//Email
			if(!isset($error['email']) AND !$errors)
			{
				$this->updateEmail($db,$_POST['email']);
				if(!$norefresh){echo'<script>
						window.location.href = "account.php"
						</script>';}
			}
			}
			
			//Phone number: let's see if it's only made out of numbers 
			if(!preg_match("'^[0-9]{9,13}[0-9]$'", $_POST['phone']) OR empty($_POST['phone'])) // There's something else than numbers
			{
			$error['phone']="Your phone number doesn't seem valid. It must contains from 9 to 13 digits.";
			$errors=true;
			}

			if($this->phone!=$_POST['phone'] AND !isset($error['phone']) AND $errors==false) // user wants to change phone
			{
				$this->updatePhone($db,$_POST['phone']);
				
			}
			
			if($this->address!=$_POST['address']  AND $errors==false) // user wants to change address
			{
				$this->updateAddress($db,$_POST['address']);
			}
			
			echo'<span>First name:</span> '.$this->firstname.'<br/>
			<span>Surname:</span> '.$this->surname.'<br/>
			<span>Age:</span> '.$this->getAge().'<br/>
			<form method="post" action="account.php">';
			if(!empty($error['email'])){
			echo'<span>Email:</span><input type="text" name="email" value="'.$_POST['email'].'" class="error"/><small style="color:red;" >'.$error['email'].'</small><br/>
			';}
			else{
			echo'<span>Email:</span> <input type="text" name="email" value="'.$this->email.'" /><br/>
			';}
			if(!empty($error['password'])){
			echo'<span>Password:</span> <input type="text" name="password" value="'.$_POST['password'].'" placeholder="Change password" class="error"/><small style="color:red;" >'.$error['password'].'</small><br/>
			';}
			else{
			echo'<span>Password:</span> <input type="password" name="password" value="false" placeholder="Change password" /><br/>
			';}
			if(!empty($error['phone'])){
			echo'<span>Phone:</span> <input type="text" name="phone" value="'.$_POST['phone'].'" class="error"/><small style="color:red;" >'.$error['phone'].'</small><br/>
			';}
			else{
			echo'<span>Phone:</span> <input type="text" name="phone" value="'.$this->phone.'"/><br/>
			';}
			echo'<span>Address:</span> <textarea name="address" style="min-height: 100px;" >'.$this->address.' </textarea><br/>
			<input type="hidden" name="op" value="edituser"/>
			<input type="submit" class="btn btn-primary" style="height:50px; font-size: 2em;" value="Save"/>
			</form>';
			
		}
		else{
		echo'<span>First name:</span> '.$this->firstname.'<br/>
			<span>Surname:</span> '.$this->surname.'<br/>
			<span>Age:</span> '.$this->getAge().'<br/>
			<form method="post" action="account.php">
			<span>Email:</span> <input type="text" name="email" value="'.$this->email.'" /><br/>
			<span>Password:</span> <input type="password" name="password" value="false" placeholder="Change password" /><br/>
			<span>Phone:</span> <input type="text" name="phone" value="'.$this->phone.'"/><br/>
			<span>Address:</span> <textarea name="address" style="min-height: 100px;" >'.$this->address.' </textarea><br/>
			<input type="hidden" name="op" value="edituser"/>
			<input type="submit" class="btn btn-primary" value="Edit"/>
			</form> ';
		}	
    }
}
?>